$(function () {
      class GoodList {
            constructor() {
                  this.usermsg = JSON.parse(sessionStorage.getItem("usermsg"));
                  if (this.usermsg !== null) {
                        this.writeUserMsg();
                  }
                  this.data = null;
                  this.cart_data = this.getCartData();
                  this.init().then(res => {
                        this.data = res.data
                        Object.assign(this, {
                              // 一页默认显示十条数据; 
                              show_num: 20,
                              // 当前的页码 ; 
                              index: 0,
                              // 分页内容总条数; 
                              count: this.data.count,
                              // 中间显示的页码数量; 
                              show_page_count: 5

                        }, 20)
                        this.container = $(".goodsList");
                        this.pagination = $(".pagination");
                        this.total_page_num = Math.ceil(this.count / this.show_num);
                        // show_page_count 数据必须是奇数;
                        if (this.show_page_count % 2 !== 1) {
                              this.show_page_count++;
                        }
                        this.renderBullet();
                        this.render();
                        $("#goodsnum").html(this.data.count)
                        new lazyLoad("#goodsList .goods-item img")
                        this.bindEvent();
                  })

            }
            init() {
                  let options = {
                        url: "http://localhost:3000/static/data/dataAll.json"
                  }
                  return axios(options)
            }
            writeUserMsg() {
                  $(".right-login1").css({
                        display: "none"
                  })
                  $(".right-login2").css({
                        display: "inline-block"
                  })
                  $("#login-n").html(this.usermsg.username)
            }
            renderBullet() {
                  //创建结构的核心在于，当前页面有多少条数据; 
                  // - 总页数计算方式 : 总数量 / 每页显示数量 向上取整  
                  let html = "";

                  html += "<em class='prev'><</em>"
                  html += "<strong class='start'>首页</strong>"

                  // start : 页码的起始点; 
                  // end   : 页码的终点; 

                  let start = this.index - 1;
                  let end = this.index + 3;


                  // - 判定分页的起始点; 
                  if (this.index <= 2) {
                        start = 1;
                        end = start + this.show_page_count;
                  }

                  //  this.total_page_num > this.show_page_count + 1  && this.index   : 
                  if (this.total_page_num > this.show_page_count + 1 && this.index >= this.total_page_num - 2) {
                        end = this.total_page_num;
                        start = end - 5;
                  }

                  // - end 极值判断; 
                  // - end 的最大值不能超过页码总数; 

                  if (end >= this.total_page_num) {
                        end = this.total_page_num;
                  }
                  if (!(this.total_page_num > this.show_page_count + 1)) {
                        start = 1;
                  }

                  if (this.total_page_num > this.show_page_count + 1 && this.index >= 3) {
                        html += "<span>1</span>"
                        html += "<b>...</b>"
                  }

                  // 带有省略号的渲染; 
                  for (let i = start; i <= end; i++) {
                        html += `<span ${i - 1 === this.index ? "class='active'" : ""}>${i}</span>`
                  }

                  if (this.total_page_num > this.show_page_count + 1 && this.index <= this.total_page_num - 4) {
                        html += "<b>...</b>"
                        html += "<span>" + this.total_page_num + "</span>"
                  }

                  html += "<strong class='end'>末尾</strong>"
                  html += "<em class='next'>></em>"

                  $(".pagination").html(html)
            }

            add() {
                  if (this.index >= this.total_page_num - 1) {
                        return false;
                  }
                  this.index++
                  this.render();
                  this.renderBullet();
            }
            reduce() {
                  if (this.index <= 0) {
                        return false;
                  }
                  this.index--
                  this.render();
                  this.renderBullet();
            }
            bindEvent() {
                  // 进入详情页
                  $("#goodsList").on("click", ".goods-item", (e) => {
                        let id = $(e.target).attr("data-id")
                        if(id){
                              this.go(id);
                        }else{
                              return false
                        }
                  })

                  // 列表页添加购物车
                  $("#goodsList").on("click", ".goods-action", (e) => {
                        let id = $(e.target).attr("data-id")
                        let res = this.search(id)
                        // 新增数据 : 
                        if(res){
                              this.addCart(id, res);
                              $(".shopcaert").css({
                                    display : "block"
                              })
                        }else{
                              $(".shopcaerterr").css({
                                    display : "block"
                              })
                        }
                  })

                  // 加入购物车成功的弹框
                  $("#shopcart").on("click", ".sucimg1", (e) => {
                        $(".shopcaert").css({
                              display : "none"
                        })
                  })
                  $("#shopcart").on("click", ".gobuyshop", (e) => {
                        $(".shopcaert").css({
                              display : "none"
                        })
                  })
                  $("#shopcart").on("click", ".goshopcart", (e) => {
                        $(".shopcaert").css({
                              display : "none"
                        })
                        location.href = "./shopCar.html";
                  })

                  // 加入购物车失败的弹框
                  $("#shopcarterr").on("click", ".errimg1", (e) => {
                        $(".shopcaerterr").css({
                              display : "none"
                        })
                  })
                  $("#shopcarterr").on("click", ".errbtn", (e) => {
                        $(".shopcaerterr").css({
                              display : "none"
                        })
                  })

                  $.onclick = () => {
                        g.remove(2);
                  }

                  // 分页器
                  $(".pagination").on("click", "span", (e) => {
                        this.index = $(e.target).text() - 1;
                        this.render();
                        this.renderBullet();
                  })
                  $(".pagination").on("click", ".start", (e) => {
                        this.index = 0;
                        this.render();
                        this.renderBullet();
                  })
                  $(".pagination").on("click", ".end", (e) => {
                        this.index = this.total_page_num - 1;
                        this.render();
                        this.renderBullet();
                  })
                  $(".pagination").on("click", ".next", (e) => {
                        this.add();
                  })
                  $(".pagination").on("click", ".prev", (e) => {
                        this.reduce();
                  })
                  $(".pagination").click("selectstart", (e) => {
                        e.preventDefault();
                  })

                  // 范围搜索
                  $(".entries").on("click", ".handle", (e) => {
                        var brr = []
                        brr = $(e.target).text().split("-")
                        this.init().then(res => {
                              this.data = res.data;
                              this.range(brr)
                        })

                  })
                  // 价格排序
                  // 升序
                  $(".pricesort").on("click", "#pricesortadd", (e) => {
                        this.dataFil();
                  })
                  // 降序
                  $(".pricesort").on("click", "#pricesortreduce", (e) => {
                        this.datareduce();
                  })
                  // 清空筛选
                  $(".pricesort").on("click", "#emptyscreen", (e) => {
                        this.init().then(res => {
                              this.data = res.data
                              Object.assign(this, {
                                    // 一页默认显示十条数据; 
                                    show_num: 20,
                                    // 当前的页码 ; 
                                    index: 0,
                                    // 分页内容总条数; 
                                    count: this.data.count,
                                    // 中间显示的页码数量; 
                                    show_page_count: 5

                              }, 20)
                              this.container = $(".goodsList");
                              this.pagination = $(".pagination");
                              this.total_page_num = Math.ceil(this.count / this.show_num);
                              // show_page_count 数据必须是奇数;
                              if (this.show_page_count % 2 !== 1) {
                                    this.show_page_count++;
                              }
                              this.renderBullet();
                              this.render();
                              $("#goodsnum").html(this.data.count)
                              new lazyLoad("#goodsList .goods-item img")
                        })
                  })

                  $(window).scroll((e) => {
                        let scrolltop = $(document).scrollTop()
                        if (scrolltop > 700) {
                            $("#fixedfield").css({
                                display: "block"
                            })
                        } else {
                            $("#fixedfield").css({
                                display: "none"
                            })
                        }
                    }) 
                  // 返回顶部
                  $("#fixedfield").on("click", ".grouptop", (e) => {
                        $("body,html").animate(
                              {
                                    scrollTop: 0
                              },
                              800
                        );
                  })

                  // 加载更多
                  $(".center").on("click","#more",(e) => {
                        $(".center .page").css({
                              height : "auto"
                        })
                        $(".more").css({
                              display : "none"
                        })
                        $(".less").css({
                              display : "block"
                        })
                  })
                  // 收起加载内容
                  $(".center").on("click","#less",(e) => {
                        $(".center .page").css({
                              height : "930px"
                        })
                        $(".more").css({
                              display : "block"
                        })
                        $(".less").css({
                              display : "none"
                        })
                  })
            }
            range(res) {
                  var arr = [];
                  for (var i = 0; i < res.length; i++) {
                        this.data.data.filter(item => {
                              if (res[0] <= item.price && item.price <= res[i]) {
                                    arr.push(item)
                              }
                        })
                  }
                  this.data = []
                  this.data["data"] = arr;
                  this.data["count"] = arr.length
                  Object.assign(this.data, {
                        // 一页默认显示十条数据; 
                        show_num: 20,
                        // 当前的页码 ; 
                        index: 0,
                        // 分页内容总条数; 
                        count: this.data.count,
                        // 中间显示的页码数量; 
                        show_page_count: 5

                  }, 20)
                  this.container = $(".goodsList");
                  this.pagination = $(".pagination");
                  this.total_page_num = Math.ceil(this.data.count / this.show_num);
                  // show_page_count 数据必须是奇数;
                  if (this.show_page_count % 2 !== 1) {
                        this.show_page_count++;
                  }
                  // 防止数据缓存
                  this.index = 0;
                  this.renderBullet();
                  this.render();
                  $("#goodsnum").html(this.data.count)
                  new lazyLoad("#goodsList .goods-item img")

            }
            dataFil() {
                  var arr = []
                  this.data.data.filter(item => {
                        if (item.price) {
                              let price = item.price
                              arr.push(price)
                        }
                  })
                  this.maopao(arr)
                  var brr = []
                  for (var i = 0; i < arr.length; i++) {
                        this.data.data.filter(item => {
                              if (arr[i] === item.price) {
                                    brr.push(item)
                              }
                        })
                  }
                  let crr = this.noRepeat(brr)
                  this.data["data"] = crr;
                  this.render()
            }
            datareduce() {
                  var arr = []
                  this.data.data.filter(item => {
                        if (item.price) {
                              let price = item.price
                              arr.push(price)
                        }
                  })
                  this.maopao(arr).reverse()
                  var brr = []
                  for (var i = 0; i < arr.length; i++) {
                        this.data.data.filter(item => {
                              if (arr[i] === item.price) {
                                    brr.push(item)
                              }
                        })
                  }
                  let crr = this.noRepeat(brr)
                  this.data["data"] = crr;
                  this.render()
            }
            noRepeat(arr) {
                  for (var i = 0; i < arr.length; i++) {
                        // 每一条要和后方所有数据比对的数据; 
                        var item = arr[i];
                        for (var k = i + 1; k < arr.length; k++) {
                              // 如果当前项和数组后面的项相同，那么我们就删除这条数据; 
                              if (item === arr[k]) {
                                    // 我们在删除数组项之后，会跳过一个位置的数据比对; 
                                    arr.splice(k, 1);
                                    // 为了不跳过数据的比对，我们在删除数据之后，重新比对当前位置的数据; 
                                    k--;
                              }
                        }
                  }
                  return arr;
            }
            maopao(arr) {
                  for (var i = 0; i < arr.length - 1; i++) {
                        for (var j = 0; j < arr.length - i - 1; j++) {
                              if (arr[j] > arr[j + 1]) {
                                    var temp = arr[j];
                                    arr[j] = arr[j + 1];
                                    arr[j + 1] = temp;
                              }
                        }
                  }
                  return arr;
            }
            go(id) {
                  location.href = "./details.html#id=" + id;
            }
            remove(id) {
                  delete this.cart_data[id];
                  this.save();
            }
            render() {
                  let html = "";
                  // this.
                  for (let i = this.index * this.show_num; i < (this.index + 1) * this.show_num; i++) {
                        // 如果渲染的数据不存在，那么我们就略过本次拼接;
                        if (this.data.data[i] === undefined) continue;
                        html += `
                        <li  data-id="${this.data.data[i].product_id}">
                        <div class="goods-item">
                         <div class="goods-pic">
                              <div class="relative">
                                    <img class="action-goods-img" data-id="${this.data.data[i].product_id}"
                                          src="${this.data.data[i].img_url}"
                                          alt="">
                              </div>
                         </div>
                         <div class="goods-info">
                              <h3 class="goods-name">
                                    <div class="title">
                                          <p data-id="${this.data.data[i].product_id}">${this.data.data[i].product_name}</p>
                                          <p data-id="${this.data.data[i].product_id}">${this.data.data[i].subtitle}</p>
                                    </div>
                              </h3>
                              <div class="goods-price">
                                    <ins class="price">￥${this.data.data[i].price}</ins>
                              </div>
                              <div class="promotion-tags">
                                    <span class="tag">限时</span>
                                    <span class="tag">赠品</span>
                              </div>
                        </div>
                        </div>
                        <div class="goods-action">
                              <div class="news_btns">
                                    <div class="news_btn_rigth">
                                          <div class="news_addcart">
                                                <span id="goodsId" data-id="${this.data.data[i].product_id}">加入购物车</span>
                                          </div>
                                    </div>
                              </div>
                        </div>
                        
                  </li>
                    `
                  }
                  $("#goodsList").html(html)
            }

            search(id) {
                  let res = null;
                  let good_data = this.data
                  good_data.data.some(item => {
                        if (Number(id) === Number(item.product_id)) {
                              res = item;
                              return true;
                        }
                  })
                  return res;
            }
            getCartData() {
                  try {
                        let data = JSON.parse(localStorage.getItem("cart"))
                        if (data === null) {
                              return {}
                        }
                        return data;
                  } catch (e) {
                        return {};
                  }
            }
            addCart(id, data) {
                  // 判断当前的id是否存在于购物车列表之中
                  if (id in this.cart_data) {
                        // 如果存在就让商品数量自增; 
                        this.cart_data[id].count++;
                  } else {
                        // 如果不存在就放入一个初始数据; 
                        data.count = 1;
                        this.cart_data[id] = data;
                  }
                  this.save();
            }
            save() {
                  localStorage.setItem("cart", JSON.stringify(this.cart_data));
            }



      }
      new GoodList;
})